package com.github.nuggets.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.nuggets.constant.auth.AccountRoleConstants;
import com.github.nuggets.entity.Account;
import com.github.nuggets.model.entity.NuggetsAccountEntity;
import com.github.nuggets.model.exception.BizException;
import com.github.nuggets.model.exception.ParamInvalidException;
import com.github.nuggets.model.param.AccountUpdateParams;
import com.github.nuggets.model.param.PasswordUpdateParams;
import com.github.nuggets.model.pojo.LoginAccountInfo;
import com.github.nuggets.model.vo.NuggetsAccountDetailVO;
import com.github.nuggets.repository.AccountRepository;
import com.github.nuggets.service.AccountManagerService;
import com.github.nuggets.util.DateUtils;
import com.github.nuggets.util.LoginAccountUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: wangsj
 * @date: 2022/3/17 5:48 下午
 */
@Service
public class AccountManagerServiceImpl implements AccountManagerService {
    @Autowired
    AccountRepository accountRepository;


    @Override
    public Boolean registered(Account account) {
        NuggetsAccountEntity nuggetsAccountEntity = new NuggetsAccountEntity();
        BeanUtil.copyProperties(account, nuggetsAccountEntity);

        //用户名查重
        if (accountRepository.isUserNameExist(nuggetsAccountEntity.getUserName())) {
            throw new BizException("用户名" + account.getUserName() + "已被注册，请重新输入！");
        }

        //第一次注册默认为普通用户
        nuggetsAccountEntity.setRole(AccountRoleConstants.ROLE_USER);
        nuggetsAccountEntity.setNickName(nuggetsAccountEntity.getUserName());

        return accountRepository.save(nuggetsAccountEntity);
    }

    @Override
    public Account findAccount(String userName) {
        Account account = new Account();
        accountRepository.getAccountInfoByUserName(userName)
                .ifPresent(nuggetsAccountEntity -> BeanUtil.copyProperties(nuggetsAccountEntity, account));

        return account;
    }

    @Override
    public NuggetsAccountDetailVO findAccountDetails(Long accountId) {
        NuggetsAccountEntity account = Optional.ofNullable(accountRepository.getById(accountId))
                .orElseThrow(() -> new BizException("用户不存在"));

        NuggetsAccountDetailVO detailVO = new NuggetsAccountDetailVO();
        BeanUtil.copyProperties(account,detailVO);

        detailVO.setCreateTime(account.getCreateTime().format(DateUtils.FORMATTER_YYYY_MM_DD_HH_MM_SS));

        return detailVO;
    }

    @Override
    public List<NuggetsAccountDetailVO> findAccounts(String searchParam) {

        List<NuggetsAccountEntity> nuggetsAccountEntities = accountRepository.list(new LambdaQueryWrapper<NuggetsAccountEntity>()
                .like(NuggetsAccountEntity::getUserName, searchParam)
                .or()
                .like(NuggetsAccountEntity::getEmail, searchParam)
                .or()
                .like(NuggetsAccountEntity::getGithubAccount, searchParam)
                .or()
                .like(NuggetsAccountEntity::getNickName, searchParam)
                .or()
                .like(NuggetsAccountEntity::getCompanyName, searchParam)
        );

        return nuggetsAccountEntities.stream().map(account-> {
            NuggetsAccountDetailVO detailVO = new NuggetsAccountDetailVO();
            BeanUtil.copyProperties(account,detailVO);
            return detailVO;
        }).collect(Collectors.toList());
    }

    @Override
    public NuggetsAccountDetailVO findLoginAccountDetails(OAuth2Authentication auth) {
        //获取登录用户
        LoginAccountInfo loginAccount = LoginAccountUtils.getLoginAccount(auth);
        //获取详情
        NuggetsAccountDetailVO details = this.findAccountDetails(loginAccount.getId());
        details.setLoginTime(loginAccount.getLoginTime());
        return  details;
    }

    @Override
    public Boolean updateAccount(Long accountId, AccountUpdateParams updatePrams) {
        NuggetsAccountEntity account = Optional.ofNullable(
                accountRepository.getById(accountId)
        ).orElseThrow(() -> new BizException("用户不存在"));


        BeanUtil.copyProperties(updatePrams,account);

        return accountRepository.updateById(account);
    }

    @Override
    public Boolean updatePassword(Long accountId, PasswordUpdateParams updateParams) {
        if (!updateParams.getNewPasswordFirst().equals(updateParams.getNewPasswordSecond())){
            throw new ParamInvalidException("两次输入的密码不同");
        }
        NuggetsAccountEntity account = Optional.ofNullable(
                accountRepository.getById(accountId)
        ).orElseThrow(() -> new BizException("用户不存在"));

        if (!account.getPassword().equals(updateParams.getOldPassword())){
            throw new ParamInvalidException("旧密码错误");
        }
        if (account.equals(updateParams.getNewPasswordSecond())){
            throw new BizException("新密码不能与旧密码相同");
        }

        account.setPassword(updateParams.getNewPasswordSecond());

        return accountRepository.updateById(account);
    }

    @Override
    public Boolean removeAccount(Long accountId) {
        NuggetsAccountEntity account = Optional.ofNullable(
                accountRepository.getById(accountId)
        ).orElseThrow(() -> new BizException("用户不存在"));

        return accountRepository.removeById(account);
    }
}
